/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sciRegister.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.modelDemand.domain.ModelDemandAuditLog;
import com.fzhucc.modules.modelDemand.repository.ModelDemandAuditLogRepository;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.AllowSciPersonnelInfoDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.AuditSciPersonnelInfoDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoQueryCriteria;
import com.fzhucc.modules.sciRegister.domain.SciRegisterInfo;
import com.fzhucc.modules.sciRegister.domain.dto.*;
import com.fzhucc.modules.sciRegisterInfo.domain.SciRegisterGzInfo;
import com.fzhucc.modules.sciRegisterInfo.domain.dto.SciRegisterGzAddDto;
import com.fzhucc.modules.sciRegisterInfo.domain.dto.SciRegisterGzInfoDto;
import com.fzhucc.modules.sciRegisterInfo.repository.SciRegisterGzInfoRepository;
import com.fzhucc.modules.sciRegisterInfo.service.mapstruct.SciRegisterGzInfoMapper;
import com.fzhucc.modules.sciTdStatusLog.domain.SciTechnologyDemandPpLog;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemandInfo;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemandRecord;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.*;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.utils.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciRegister.repository.SciRegisterInfoRepository;
import com.fzhucc.modules.sciRegister.service.mapstruct.SciRegisterInfoMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-04-26
 **/
@Service
@RequiredArgsConstructor
public class SciRegisterInfoService {

    @Value("${sci.audit.qxdsh}")
    public String qxdsh;

    @Value("${sci.audit.sjdsh}")
    public String sjdsh;

    @Value("${sci.audit.shtg}")
    public String shtg;

    @Value("${sci.audit.bh}")
    public String bh;

    @Value("${sci.log.djb}")
    public String djb;

    @Value("${sci.stage.quPass}")
    public String quPass;

    @Value("${sci.stage.quNoPass}")
    public String quNoPass;

    @Value("${sci.stage.cityPass}")
    public String cityPass;

    @Value("${sci.log.gzs}")
    public String gzs;

    @Value("${sci.stage.cityNoPass}")
    public String cityNoPass;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;


    private final SciRegisterInfoRepository sciRegisterInfoRepository;
    private final SciRegisterInfoMapper sciRegisterInfoMapper;

    private final SciRegisterGzInfoMapper sciRegisterGzInfoMapper;

    private final SciRegisterGzInfoRepository sciRegisterGzInfoRepository;

    private final ModelDemandAuditLogRepository modelDemandAuditLogRepository;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final UserRepository userRepository;


    public Map<String, Object> queryAll(SciRegisterInfoQueryCriteria criteria, Pageable pageable) {
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        criteria.setIsDelete(0);
        criteria.setOrgAreas(null);
        Page<SciRegisterInfo> page = sciRegisterInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciRegisterInfoDto> map = page.map(sciRegisterInfoMapper::toDto);
        List<SciRegisterInfoDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciRegisterInfoDto dto : list) {
                //区域划分
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }
                //资金来源
                String zjSource = dto.getZjSource();
                if (zjSource != null && zjSource.contains(";")) {
                    String[] array = zjSource.split(";");
                    dto.setZjSources(array);
                } else {
                    String[] array = {};
                    dto.setZjSources(array);
                }
                //审核信息
                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), djb);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                //工种信息
                List<SciRegisterGzInfo> listGzInfo = sciRegisterGzInfoRepository.findByDjbId(dto.getId());
                List<SciRegisterGzInfoDto> sciRegisterGzInfoDtos = sciRegisterGzInfoMapper.toDto(listGzInfo);
                dto.setListGz(sciRegisterGzInfoDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAllh5(SciRegisterInfoQueryCriteria criteria, Pageable pageable) {
        criteria.setIsDelete(0);
        if (criteria.getOrgArea() != null && criteria.getOrgArea().equals(all)) {
            //h5的直接传orgArea
            criteria.setOrgArea(null);
        }
        Page<SciRegisterInfo> page = sciRegisterInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciRegisterInfoDto> map = page.map(sciRegisterInfoMapper::toDto);
        List<SciRegisterInfoDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciRegisterInfoDto dto : list) {
                //区域划分
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }
                //资金来源
                String zjSource = dto.getZjSource();
                if (zjSource != null && zjSource.contains(";")) {
                    String[] array = zjSource.split(";");
                    dto.setZjSources(array);
                } else {
                    String[] array = {};
                    dto.setZjSources(array);
                }
                //审核信息
                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), djb);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                //工种信息
                List<SciRegisterGzInfo> listGzInfo = sciRegisterGzInfoRepository.findByDjbId(dto.getId());
                List<SciRegisterGzInfoDto> sciRegisterGzInfoDtos = sciRegisterGzInfoMapper.toDto(listGzInfo);
                dto.setListGz(sciRegisterGzInfoDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> my(SciRegisterInfoQueryCriteria criteria, Pageable pageable) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        Page<SciRegisterInfo> page = sciRegisterInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciRegisterInfoDto> map = page.map(sciRegisterInfoMapper::toDto);
        List<SciRegisterInfoDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciRegisterInfoDto dto : list) {
                //区域划分
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }
                //资金来源
                String zjSource = dto.getZjSource();
                if (zjSource != null && zjSource.contains(";")) {
                    String[] array = zjSource.split(";");
                    dto.setZjSources(array);
                } else {
                    String[] array = {};
                    dto.setZjSources(array);
                }
                //审核信息
                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), djb);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                //工种信息
                List<SciRegisterGzInfo> listGzInfo = sciRegisterGzInfoRepository.findByDjbId(dto.getId());
                List<SciRegisterGzInfoDto> sciRegisterGzInfoDtos = sciRegisterGzInfoMapper.toDto(listGzInfo);
                dto.setListGz(sciRegisterGzInfoDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    public List<SciRegisterInfoDto> queryAll(SciRegisterInfoQueryCriteria criteria) {
        //导出  如果有传则按传的数组 导出
        criteria.setIsDelete(0);
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        return sciRegisterInfoMapper.toDto(sciRegisterInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public List<SciRegisterInfoDto> queryAllmy(SciRegisterInfoQueryCriteria criteria) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        return sciRegisterInfoMapper.toDto(sciRegisterInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    //根据不同设置不同的部门查看
    public String setCriteria(SciRegisterInfoQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && (orgArea.equals(all) || orgArea.equals(all2))) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void isAllowEdit(AllowSciRegisterInfoDto dto) {
        Optional<SciRegisterInfo> res = sciRegisterInfoRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到登记表id");
        }
        Integer isEdit = dto.getIsEdit();
        if (isEdit == null) {
            throw new BadRequestException("缺少参数");
        }
        if (isEdit != 0 && isEdit != 1) {
            throw new BadRequestException("参数错误无法操作");
        }
        SciRegisterInfo info = res.get();
        info.setIsEdit(isEdit);
        sciRegisterInfoRepository.save(info);
    }

    @Transactional
    public SciRegisterInfoDto findById(Integer id) {
        SciRegisterInfo sciRegisterInfo = sciRegisterInfoRepository.findById(id).orElseGet(SciRegisterInfo::new);
        ValidationUtil.isNull(sciRegisterInfo.getId(), "SciRegisterInfo", "id", id);
        SciRegisterInfoDto dto = sciRegisterInfoMapper.toDto(sciRegisterInfo);

        //区域划分
        String orgArea = dto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            dto.setOrgAreas(array);
        } else {
            String[] array = {};
            dto.setOrgAreas(array);
        }
        //资金来源
        String zjSource = dto.getZjSource();
        if (zjSource != null && zjSource.contains(";")) {
            String[] array = zjSource.split(";");
            dto.setZjSources(array);
        } else {
            String[] array = {};
            dto.setZjSources(array);
        }
        //审核信息
        List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), djb);
        dto.setListModelDemandAuditLog(modelDemandAuditLogs);

        //工种信息
        List<SciRegisterGzInfo> listGzInfo = sciRegisterGzInfoRepository.findByDjbId(dto.getId());
        List<SciRegisterGzInfoDto> sciRegisterGzInfoDtos = sciRegisterGzInfoMapper.toDto(listGzInfo);
        dto.setListGz(sciRegisterGzInfoDtos);
        return dto;
    }

    @Transactional(rollbackFor = Exception.class)
    public SciRegisterInfoDto create(SciRegisterInfoAddDto dto) {
        SciRegisterInfo resources = new SciRegisterInfo();
        resources.setName(dto.getName());
        resources.setUnit(dto.getUnit());
        resources.setEstablish(dto.getEstablish());
        resources.setPhone(dto.getPhone());
        resources.setJg(dto.getJg());
        resources.setCurator(dto.getCurator());
        resources.setCuratorPhone(dto.getCuratorPhone());
        resources.setTele(dto.getTele());
        resources.setJe(dto.getJe());
        resources.setPlace(dto.getPlace());
        resources.setMj(dto.getMj());
        resources.setJzmj(dto.getJzmj());
        resources.setJsModel(dto.getJsModel());
        resources.setAll(dto.getAll());
        resources.setZz(dto.getZz());
        resources.setJz(dto.getJz());
        resources.setJs(dto.getJs());
        resources.setJs1(dto.getJs1());
        resources.setGl(dto.getGl());
        resources.setGl1(dto.getGl1());
        resources.setQt(dto.getQt());
        resources.setQt1(dto.getQt1());
        resources.setZhuanji(dto.getZhuanji());
        resources.setZhuanji1(dto.getZhuanji1());
        resources.setZg(dto.getZg());
        resources.setZg1(dto.getZg1());
        resources.setFg(dto.getFg());
        resources.setFg1(dto.getFg1());
        resources.setZj(dto.getZj());
        resources.setZj1(dto.getZj1());
        resources.setRc(dto.getRc());
        resources.setRc1(dto.getRc1());
        resources.setGaoji(dto.getGaoji());
        resources.setGaoji1(dto.getGaoji1());
        resources.setJishi(dto.getJishi());
        resources.setJishi1(dto.getJishi1());
        resources.setGjg(dto.getGjg());
        resources.setGjg1(dto.getGjg1());
        resources.setZhongji(dto.getZhongji());
        resources.setZhongji1(dto.getZhongji1());
        resources.setChuji(dto.getChuji());
        resources.setChuji1(dto.getChuji1());
        resources.setQtj(dto.getQtj());
        resources.setQtj1(dto.getQtj1());
        resources.setXxKc(dto.getXxKc());
        resources.setXsKc(dto.getXsKc());
        resources.setXxYpx(dto.getXxYpx());
        resources.setXsYpx(dto.getXsYpx());
        resources.setXsSc(dto.getXsSc());
        resources.setIsXsJs(dto.getIsXsJs());
        resources.setXsDetails(dto.getXsDetails());
        resources.setJbDetails(dto.getJbDetails());
        resources.setSbDetails(dto.getSbDetails());
        resources.setNlDetails(dto.getNlDetails());
        resources.setZyDetails(dto.getZyDetails());
        resources.setGhDetails(dto.getGhDetails());
        resources.setKnDetails(dto.getKnDetails());
        resources.setFzDetails(dto.getFzDetails());
        resources.setOtherDetails(dto.getOtherDetails());
        resources.setUserId(SecurityUtils.getCurrentUserId());
        resources.setPic(dto.getPic());
        resources.setContacts(dto.getContacts());
        resources.setIsEdit(0);//设置默认添加不可编辑
        resources.setEmail(dto.getEmail());
        resources.setHot(0);
        resources.setAddress(dto.getAddress());
        resources.setIsDelete(0);
        resources.setIsShow(0);
        resources.setSort(1);
        resources.setAuditStatus(qxdsh);//区县待审核
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        if (dto.getZjSources() != null && dto.getZjSources().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getZjSources()) {
                last = last + a + ";";
            }
            resources.setZjSource(last);
        } else {
            resources.setZjSource(null);
        }
        SciRegisterInfoDto sciRegisterInfoDto = sciRegisterInfoMapper.toDto(sciRegisterInfoRepository.save(resources));
        //根据id设置sort
        Optional<SciRegisterInfo> result = sciRegisterInfoRepository.findById(sciRegisterInfoDto.getId());
        if (result.isPresent()) {
            SciRegisterInfo sciRegisterInfo = result.get();
            sciRegisterInfo.setSort(sciRegisterInfo.getId());
            sciRegisterInfoRepository.save(sciRegisterInfo);
        }
        List<SciRegisterGzAddDto> gzList = dto.getGzList();
        if (gzList != null && gzList.size() > 0) {
            for (SciRegisterGzAddDto res : gzList) {
                SciRegisterGzInfo sciRegisterGzInfo = new SciRegisterGzInfo();
                sciRegisterGzInfo.setRiId(sciRegisterInfoDto.getId());
                sciRegisterGzInfo.setCount(res.getCount());
                sciRegisterGzInfo.setName(res.getName());
                sciRegisterGzInfoRepository.save(sciRegisterGzInfo);
            }
        }
        return sciRegisterInfoDto;
    }

    public List<DictDetailDto> getIsXsJs() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("is_xs_js");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getJsModel() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("js_model");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getZjSource() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("zj_source");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(SciRegisterInfoEditDto dto) {
        SciRegisterInfo sciRegisterInfo = sciRegisterInfoRepository.findById(dto.getId()).orElseGet(SciRegisterInfo::new);
        ValidationUtil.isNull(sciRegisterInfo.getId(), "SciRegisterInfo", "id", dto.getId());

        sciRegisterInfo.setPic(dto.getPic());
        sciRegisterInfo.setContacts(dto.getContacts());
        sciRegisterInfo.setEmail(dto.getEmail());
        sciRegisterInfo.setAddress(dto.getAddress());
        //sciRegisterInfo.setUserId(SecurityUtils.getCurrentUserId());
        sciRegisterInfo.setIsDelete(dto.getIsDelete());
        //sciRegisterInfo.setAuditStatus(dto.getAuditStatus());
        sciRegisterInfo.setIsShow(dto.getIsShow());
        sciRegisterInfo.setSort(dto.getSort());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            sciRegisterInfo.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            sciRegisterInfo.setOrgArea(orgAreaReturn());
        }
        sciRegisterInfo.setName(dto.getName());
        sciRegisterInfo.setUnit(dto.getUnit());
        sciRegisterInfo.setEstablish(dto.getEstablish());
        sciRegisterInfo.setPhone(dto.getPhone());
        sciRegisterInfo.setJg(dto.getJg());
        sciRegisterInfo.setCurator(dto.getCurator());
        sciRegisterInfo.setCuratorPhone(dto.getCuratorPhone());
        sciRegisterInfo.setTele(dto.getTele());
        sciRegisterInfo.setJe(dto.getJe());
        sciRegisterInfo.setPlace(dto.getPlace());
        sciRegisterInfo.setMj(dto.getMj());
        sciRegisterInfo.setJzmj(dto.getJzmj());
        sciRegisterInfo.setJsModel(dto.getJsModel());
        sciRegisterInfo.setAll(dto.getAll());
        sciRegisterInfo.setZz(dto.getZz());
        sciRegisterInfo.setJz(dto.getJz());
        sciRegisterInfo.setJs(dto.getJs());
        sciRegisterInfo.setJs1(dto.getJs1());
        sciRegisterInfo.setGl(dto.getGl());
        sciRegisterInfo.setGl1(dto.getGl1());
        sciRegisterInfo.setQt(dto.getQt());
        sciRegisterInfo.setQt1(dto.getQt1());
        sciRegisterInfo.setZhuanji(dto.getZhuanji());
        sciRegisterInfo.setZhuanji1(dto.getZhuanji1());
        sciRegisterInfo.setZg(dto.getZg());
        sciRegisterInfo.setZg1(dto.getZg1());
        sciRegisterInfo.setFg(dto.getFg());
        sciRegisterInfo.setFg1(dto.getFg1());
        sciRegisterInfo.setZj(dto.getZj());
        sciRegisterInfo.setZj1(dto.getZj1());
        sciRegisterInfo.setRc(dto.getRc());
        sciRegisterInfo.setRc1(dto.getRc1());
        sciRegisterInfo.setGaoji(dto.getGaoji());
        sciRegisterInfo.setGaoji1(dto.getGaoji1());
        sciRegisterInfo.setJishi(dto.getJishi());
        sciRegisterInfo.setJishi1(dto.getJishi1());
        sciRegisterInfo.setGjg(dto.getGjg());
        sciRegisterInfo.setGjg1(dto.getGjg1());
        sciRegisterInfo.setZhongji(dto.getZhongji());
        sciRegisterInfo.setZhongji1(dto.getZhongji1());
        sciRegisterInfo.setChuji(dto.getChuji());
        sciRegisterInfo.setChuji1(dto.getChuji1());
        sciRegisterInfo.setQtj(dto.getQtj());
        sciRegisterInfo.setQtj1(dto.getQtj1());
        sciRegisterInfo.setXxKc(dto.getXxKc());
        sciRegisterInfo.setXsKc(dto.getXsKc());
        sciRegisterInfo.setXxYpx(dto.getXxYpx());
        sciRegisterInfo.setXsYpx(dto.getXsYpx());
        sciRegisterInfo.setXsSc(dto.getXsSc());
        sciRegisterInfo.setIsXsJs(dto.getIsXsJs());
        sciRegisterInfo.setXsDetails(dto.getXsDetails());
        sciRegisterInfo.setJbDetails(dto.getJbDetails());
        sciRegisterInfo.setSbDetails(dto.getSbDetails());
        sciRegisterInfo.setNlDetails(dto.getNlDetails());
        sciRegisterInfo.setZyDetails(dto.getZyDetails());
        sciRegisterInfo.setGhDetails(dto.getGhDetails());
        sciRegisterInfo.setKnDetails(dto.getKnDetails());
        sciRegisterInfo.setFzDetails(dto.getFzDetails());
        sciRegisterInfo.setOtherDetails(dto.getOtherDetails());
        if (dto.getZjSources() != null && dto.getZjSources().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getZjSources()) {
                last = last + a + ";";
            }
            sciRegisterInfo.setZjSource(last);
        } else {
            sciRegisterInfo.setZjSource(null);
        }
        SciRegisterInfo save = sciRegisterInfoRepository.save(sciRegisterInfo);
        List<SciRegisterGzAddDto> gzList = dto.getGzList();
        if (gzList != null && gzList.size() > 0) {
            for (SciRegisterGzAddDto res : gzList) {
                SciRegisterGzInfo sciRegisterGzInfo = new SciRegisterGzInfo();
                sciRegisterGzInfo.setRiId(save.getId());
                sciRegisterGzInfo.setCount(res.getCount());
                sciRegisterGzInfo.setName(res.getName());
                sciRegisterGzInfoRepository.save(sciRegisterGzInfo);
            }
        }


    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //sciRegisterInfoRepository.deleteById(id);
            //假删除
            Optional<SciRegisterInfo> res = sciRegisterInfoRepository.findById(id);
            if (res.isPresent()) {
                SciRegisterInfo sciRegisterInfo = res.get();
                sciRegisterInfo.setIsDelete(1);
                Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
                sciRegisterInfo.setDeleteTime(currentTimestamp);
                sciRegisterInfoRepository.save(sciRegisterInfo);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void auditSciRegisterInfo(AuditSciRegisterInfoDto dto) {
        Optional<SciRegisterInfo> res = sciRegisterInfoRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到登记表id");
        }
        String cAuditStatus = dto.getAuditStatus();
        if (cAuditStatus == null || cAuditStatus.equals("")) {
            throw new BadRequestException("缺少审核状态");
        }
        SciRegisterInfo sciRegisterInfo = res.get();
        //TODO 根据登录用户如果是市 的则审核市的字段    如果是区的则审核区的字段  admin暂不处理
        Long userId = SecurityUtils.getCurrentUserId();
        Optional<User> resUser = userRepository.findById(userId);
        if (!resUser.isPresent()) {
            throw new BadRequestException("未找到登录用户");
        }
        User user = resUser.get();
        String orgArea = user.getOrgArea();
        //TODO 如果orgArea里面有2个 ; 表示市级审核   3个; 表示区级审核  其他则不与通过
        if (orgArea == null || orgArea.equals("")) {
            throw new BadRequestException("缺少地区区域无法审核");
        }
        if (!orgArea.contains(";")) {
            throw new BadRequestException("地区区域不符合规范无法审核");
        }
        String[] results = orgArea.split(";");
        if (results.length == 1) {
            throw new BadRequestException("省级账号无法审核");
        } else if (results.length == 2) {
            if (cAuditStatus.equals(bh)) {//驳回
                if (!sciRegisterInfo.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //市级审核驳回 就变成区级待审核
                sciRegisterInfo.setAuditStatus(qxdsh);
                sciRegisterInfo.setIsEdit(1);//驳回设置为可编辑
                SciRegisterInfo save = sciRegisterInfoRepository.save(sciRegisterInfo);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核驳回建议
                modelDemandAuditLog.setType(djb);
                modelDemandAuditLog.setStage(cityNoPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                if (!sciRegisterInfo.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //区级审核通过 市级审核通过则通过
                sciRegisterInfo.setAuditStatus(shtg);
                //审核通过设为显示
                sciRegisterInfo.setIsShow(1);
                if (sciRegisterInfo.getIsEdit() == 1) {

                } else {
                    sciRegisterInfo.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                SciRegisterInfo save = sciRegisterInfoRepository.save(sciRegisterInfo);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(djb);
                modelDemandAuditLog.setStage(cityPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else if (results.length == 3) {
            if (cAuditStatus.equals(bh)) {//驳回
                //区级审核
                sciRegisterInfo.setAuditStatus(cAuditStatus);
                sciRegisterInfo.setIsEdit(1);//驳回设置为可编辑
                SciRegisterInfo save = sciRegisterInfoRepository.save(sciRegisterInfo);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());
                modelDemandAuditLog.setType(djb);
                modelDemandAuditLog.setStage(quNoPass);//区审核驳回
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                //区级审核通过 变为市级待审核
                sciRegisterInfo.setAuditStatus(sjdsh);
                if (sciRegisterInfo.getIsEdit() == 1) {

                } else {
                    sciRegisterInfo.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                SciRegisterInfo save = sciRegisterInfoRepository.save(sciRegisterInfo);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(djb);
                modelDemandAuditLog.setStage(quPass);//区审核通过建议
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else {
            throw new BadRequestException("未符合的审级权限无法审核");
        }
    }

    public void download(List<SciRegisterInfoDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SciRegisterInfoDto sciRegisterInfo : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", sciRegisterInfo.getName());
            map.put("建设单位", sciRegisterInfo.getUnit());
            map.put("成立时间", sciRegisterInfo.getEstablish());
            map.put("联系人", sciRegisterInfo.getContacts());
            map.put("联系电话", sciRegisterInfo.getPhone());
            //map.put("地区组织机构区分  字典 zqx_org_area", sciRegisterInfo.getOrgArea());
            map.put("封面", sciRegisterInfo.getPic());
            map.put("是否删除", sciRegisterInfo.getIsDelete());
            map.put("区审核状态", sciRegisterInfo.getAuditStatus());
            map.put("是否小程序展示", sciRegisterInfo.getIsShow());
            map.put("排序", sciRegisterInfo.getSort());
            map.put("填报用户", sciRegisterInfo.getUserId());
            map.put("是否允许编辑默认否", sciRegisterInfo.getIsEdit());
            map.put("热度", sciRegisterInfo.getHot());
            map.put("批复机构和文件", sciRegisterInfo.getJg());
            map.put("工匠学院负责人", sciRegisterInfo.getCurator());
            map.put("工匠学院负责人联系电话", sciRegisterInfo.getCuratorPhone());
            map.put("联系电话", sciRegisterInfo.getTele());
            map.put("电子邮箱", sciRegisterInfo.getEmail());
            map.put("地址", sciRegisterInfo.getAddress());
            map.put("投资金额", sciRegisterInfo.getJe());
            map.put("是否有实体场所", sciRegisterInfo.getPlace());
            map.put("占地面积", sciRegisterInfo.getMj());
            map.put("建筑面积", sciRegisterInfo.getJzmj());
            map.put("资金来源", sciRegisterInfo.getZjSource());
            map.put("建设模式", sciRegisterInfo.getJsModel());
            map.put("总计", sciRegisterInfo.getAll());
            map.put("专职人员", sciRegisterInfo.getZz());
            map.put("兼职人员", sciRegisterInfo.getJz());
            map.put("专职教师", sciRegisterInfo.getJs());
            map.put("兼职教师", sciRegisterInfo.getJs1());
            map.put("专职管理人员", sciRegisterInfo.getGl());
            map.put("兼职管理人员", sciRegisterInfo.getGl1());
            map.put("专职其他", sciRegisterInfo.getQt());
            map.put("兼职其他", sciRegisterInfo.getQt1());
            map.put("专职专技", sciRegisterInfo.getZhuanji());
            map.put("兼职专技", sciRegisterInfo.getZhuanji1());
            map.put("专职正高", sciRegisterInfo.getZg());
            map.put("兼职正高", sciRegisterInfo.getZg1());
            map.put("专职副高", sciRegisterInfo.getFg());
            map.put("兼职副高", sciRegisterInfo.getFg1());
            map.put("专职中级", sciRegisterInfo.getZj());
            map.put("兼职中级", sciRegisterInfo.getZj1());
            map.put("专职高技能人才", sciRegisterInfo.getRc());
            map.put("兼职高技能人才", sciRegisterInfo.getRc1());
            map.put("专职高级技师", sciRegisterInfo.getGaoji());
            map.put("兼职高级技师", sciRegisterInfo.getGaoji1());
            map.put("专职技师职称", sciRegisterInfo.getJishi());
            map.put("兼职技师职称", sciRegisterInfo.getJishi1());
            map.put("专职高级工", sciRegisterInfo.getGjg());
            map.put("兼职高级工", sciRegisterInfo.getGjg1());
            map.put("专职中级工", sciRegisterInfo.getZhongji());
            map.put("兼职中级工", sciRegisterInfo.getZhongji1());
            map.put("专职初级工", sciRegisterInfo.getChuji());
            map.put("兼职初级工", sciRegisterInfo.getChuji1());
            map.put("专职其他级", sciRegisterInfo.getQtj());
            map.put("兼职其他级", sciRegisterInfo.getQtj1());
            map.put("线下培训课程数量", sciRegisterInfo.getXxKc());
            map.put("线上培训课程数量", sciRegisterInfo.getXsKc());
            map.put("线下已培训", sciRegisterInfo.getXxYpx());
            map.put("线上已培训", sciRegisterInfo.getXsYpx());
            map.put("线上时常", sciRegisterInfo.getXsSc());
            map.put("线上是否建设", sciRegisterInfo.getIsXsJs());
            map.put("线上平台情况", sciRegisterInfo.getXsDetails());
            map.put("基本情况", sciRegisterInfo.getJbDetails());
            map.put("设备基本情况", sciRegisterInfo.getSbDetails());
            map.put("能力情况", sciRegisterInfo.getNlDetails());
            map.put("专业情况", sciRegisterInfo.getZyDetails());
            map.put("工会情况", sciRegisterInfo.getGhDetails());
            map.put("困难情况", sciRegisterInfo.getKnDetails());
            map.put("下一步情况", sciRegisterInfo.getFzDetails());
            map.put("其他情况", sciRegisterInfo.getOtherDetails());
            String orgArea = sciRegisterInfo.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}